﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Redis.Library
{
    /// <summary>
    /// 该类是redis操作入口类
    /// </summary>
    public class RedisClient
    {

        //任务忙重试次数
        private static int busyRetry = 5;

        //重试等待时长(ms)
        private static int busyRetryWaitMS = 200;

        //链接实例名称
        private static string sectionName;

        private static object locker = new object();

        /// <summary>
        /// 初始化
        /// </summary>
        static RedisClient()
        {
            //组合RedisConfig
            var redisConfig = ConfigManager.config;

            //为全局变量赋值
            sectionName = redisConfig.SectionName;
            busyRetry = redisConfig.BusyRetry;
            busyRetryWaitMS = redisConfig.BusyRetryWaitMS;


            if (string.IsNullOrWhiteSpace(sectionName))
                throw new Exception("redisConfig.SectionName不能为空");

            //生成链接字符串，并初始化连接池
            lock (locker)
            {
                if (RedisConnectPoolManager.Exists(sectionName))
                    return;

                var configStr = GenerateConnectionString(redisConfig);

                if ((redisConfig.PoolSize < 1) || (redisConfig.PoolSize > 100))
                    redisConfig.PoolSize = 1;

                RedisConnectPoolManager.Create(sectionName, configStr, redisConfig.PoolSize);
            }
        }

        /// <summary>
        /// redis选择具体片操作
        /// </summary>
        /// <param name="dbIndex">片索引</param>
        /// <returns></returns>
        public static RedisExtension GetRedisDb(int dbIndex = -1)
        {
            return new RedisExtension(sectionName, dbIndex, busyRetry, busyRetryWaitMS);
        }

        /// <summary>
        /// 根据redis使用类型来生成相应的连接字符串
        /// </summary>
        /// <param name="redisConfig"></param>
        /// <returns></returns>
        private static string GenerateConnectionString(RedisConfig redisConfig)
        {
            var configStr = string.Empty;

            if (!string.IsNullOrWhiteSpace(redisConfig.Slaves))
                configStr = string.Format("{0},{1},defaultDatabase={2}", redisConfig.Masters, redisConfig.Slaves, redisConfig.DefaultDatabase);
            else
                configStr = string.Format("{0},defaultDatabase={1}", redisConfig.Masters, redisConfig.DefaultDatabase);


            if (!string.IsNullOrWhiteSpace(redisConfig.Password))
                configStr += ",password=" + redisConfig.Password;


            configStr += string.Format(",allowAdmin={0},connectRetry={1},connectTimeout={2},keepAlive={3},syncTimeout={4},abortConnect=false", redisConfig.AllowAdmin, redisConfig.ConnectRetry, redisConfig.ConnectTimeout, redisConfig.KeepAlive, redisConfig.CommandTimeout);

            if (!string.IsNullOrWhiteSpace(redisConfig.Extention))
            {
                configStr += "," + redisConfig.Extention;
            }

            return configStr;
        }
    }
}
